#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include "makeargv.h"

#define BUF_SIZE 1024
int main(int argc, char **argv) {
	while (1) {
		char input[BUF_SIZE];
		printf(">"); //print prompt symbol
		if ( fgets(input, BUF_SIZE, stdin) == NULL) { //reads input from user
			perror("Error reading input from user");
			exit(1);
		}

		//get rid of the newline character, replace with \0
		if (input[strlen(input) - 1] == '\n') {
			input[strlen(input) - 1] = '\0';
		}

		//parse input to produce command
		char **prog;
		int numTokens;
		if ( (numTokens = makeargv(input, " ", &prog)) < 0) {
			perror("makeargv error");
			//exit(2);
			continue;
		}

		//exits
		if (strcmp(input, "exit") == 0) {
			break;
		}

		printf("numTokens: %d\n", numTokens);
		int i;
		for (i = 0; i < numTokens; i++) {
			printf("token%d is %s\n", i, prog[i]);
		}

		pid_t pid;
		int status = 0;
		pid = fork();
		if (pid == 0) { //child
			//exec
			execvp(prog[0], prog);	
			perror("exec failed");
			exit(status);
			exit(0);
		} else if (pid > 0) { //parent
			wait(&status);
		} else {
			perror("failed to fork");
		}
	}
}
